package com.emm.yixun.mobile.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.adapter.NotSignedAdapter;
import com.emm.yixun.mobile.adapter.ScreenONEAdapter;
import com.emm.yixun.mobile.adapter.ScreenTWOAdapter;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.emm.yixun.mobile.model.GetCustomerList;
import com.emm.yixun.mobile.model.GetCustomerList.CustomerList;
import com.emm.yixun.mobile.model.GetDictionaryList;
import com.emm.yixun.mobile.model.GetDictionaryList.RqBusNumList;
import com.emm.yixun.mobile.model.ScreenOneModel;
import com.emm.yixun.mobile.model.ScreenOneModel.Info;
import com.emm.yixun.mobile.ui.customer.FollowUpActivity;
import com.emm.yixun.mobile.ui.customer.SearchCustomerActivity;
import com.emm.yixun.mobile.ui.web.WebActivity;
import com.eroad.product.tools.PickerView;
import com.eroad.product.tools.PickerView.onSelectListener;
import com.eroad.product.tools.PopuContent;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView;
import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView.IXListViewListener;
import cn.swu.pulltorefresh.PullToRefreshSwipeMenuListView.OnMenuItemClickListener;
import cn.swu.swipemenulistview.SwipeMenu;
import cn.swu.swipemenulistview.SwipeMenuCreator;
import cn.swu.swipemenulistview.SwipeMenuItem;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import xf.tools.Loading;

/**
 * <p>
 * <b>Title：</b> 逾期未签约 未付款 待处理公用界面
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 *
 * @author tangxin
 * @date 2016年12月6日 下午4:05:59
 */
public class NotSignedActivity extends SwipeBackActivity implements IXListViewListener {

    private static final String TAG = "NotSignedActivity";

    /**
     * 被分配对象
     */
    ArrayList<CustomerListinfo> customerList = new ArrayList<NotSignedActivity.CustomerListinfo>();

    /**
     * 1未签约 2未付款 3待处理<br>
     * <类型：1、待处理客户；2、逾期未签约；3、逾期未付款>
     */
    private String TYPED = "1";

    private String NAME = "逾期未签约";

    /**
     * 0群发短信 1批量指派
     */
    private int suretype = 0;

    /**
     * 刷新侧滑菜单listview
     */
    PullToRefreshSwipeMenuListView swip_list;

    /**
     * 适配器
     */
    NotSignedAdapter adapter;

    /**
     * 更多按钮
     */
    ImageView more_btn;

    /**
     * 取消群发
     */
    Button cancel_btn;

    /**
     * 确定群发
     */
    Button sure_btn;

    /**
     * 排序
     */
    LinearLayout tcSort;

    /**
     * 排序文字
     */
    TextView colors_text;

    /**
     * 筛选文字
     */
    TextView colors_text2;

    /**
     * 排序右边图标
     */
    ImageView icon1;

    /**
     * 筛选右边图标
     */
    ImageView icon2;

    /**
     * 筛选
     */
    LinearLayout lvScreen;

    /**
     * 菜单
     */
    PopupWindow morePoPu;

    /**
     * 菜单
     */
    View view;

    /**
     * 排序
     */
    View viewSort;

    /**
     * 排序
     */
    PopupWindow poPuSort;

    /**
     * 筛选
     */
    View viewScreen;

    /**
     * 筛选
     */
    PopupWindow poPuScreen;

    /**
     * 指派
     */
    View viewZp;

    /**
     * 指派
     */
    PopupWindow poPuZp;

    /**
     * 指派选择框选中的置业顾问
     */
    private String selectName;

    /**
     * 指派选择框选中的置业顾问 的下标
     */
    private int SelectID;

    /**
     * 标题
     */
    TextView title_main;

    /**
     * 条件选择父类布局
     */
    LinearLayout lvSelectNotSigned;

    /**
     * 返回
     */
    ImageView btBack;

    /**
     * 是否批量 false批量处理 true不做批量处理
     */
    private boolean IsDrop = true;

    /**
     * 侧滑关闭框架
     */
    private SwipeBackLayout mSwipeBackLayout;

    private int setSelect = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notsigned_activity);

        if (EmmApplication.isTips()) {
            setSelect = 3;
        }

        SetSwipeBackLayout(mSwipeBackLayout);

        BaseActivity.activity = this;

        TYPED = getIntent().getStringExtra("TYPED");
        if ("1".equals(TYPED)) {// 未签约
            TYPED = "2";
        } else if ("2".equals(TYPED)) {// 未付款
            TYPED = "3";
        } else if ("3".equals(TYPED)) {// 待处理
            TYPED = "1";
        } else if ("4".equals(TYPED)) {//未完善信息客户
            TYPED = "4";
        }

        NAME = getIntent().getStringExtra("NAME");

        initView();

        SetRelativiLayoutPadding(R.id.main_head_top_rela);

        initBtn();

        Log.v(TAG, "onCreate");
        getcustomer = new GetCustomerList();
        Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
        getCustomerList("" + setSelect, itemid1, itemid2, "" + 1, "" + pageSize, 1, TYPED);
        getDictionaryList();
    }

    /**
     * <p>
     * <b>Title：</b> 初始化view
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:11:20
     */
    private void initView() {
        more_btn = (ImageView) findViewById(R.id.customer_include).findViewById(R.id.more_btn);
        sure_btn = (Button) findViewById(R.id.customer_include).findViewById(R.id.sure_btn);
        cancel_btn = (Button) findViewById(R.id.customer_include).findViewById(R.id.cancel_btn);
        more_btn.setVisibility(View.VISIBLE);
        tcSort = (LinearLayout) findViewById(R.id.sort_textview);
        colors_text = (TextView) findViewById(R.id.colors_text);
        icon1 = (ImageView) findViewById(R.id.icon1);
        lvScreen = (LinearLayout) findViewById(R.id.screen_textview);
        colors_text2 = (TextView) findViewById(R.id.colors_text2);
        icon2 = (ImageView) findViewById(R.id.icon2);
        title_main = (TextView) findViewById(R.id.customer_include).findViewById(R.id.title_main);
        title_main.setText(NAME);
        swip_list = (PullToRefreshSwipeMenuListView) findViewById(R.id.listView);
        lvSelectNotSigned = (LinearLayout) findViewById(R.id.select_notsigned);
        btBack = (ImageView) findViewById(R.id.back_btn);
        // CreateDate();
        swip_list.setPullRefreshEnable(true);
        swip_list.setPullLoadEnable(true);
        swip_list.setXListViewListener(this);
        swip_list.setRefreshTime(EmmApplication.getData("RefreshTime"));

        initMenuListView();
    }

    public class CustomerListinfo {
        private String customerId;// 被分配客户

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }
    }

    /**
     * <p>
     * <b>Title：</b> 初始化监听事件
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:13:40
     */
    private void initBtn() {
        btBack.setVisibility(View.VISIBLE);
        btBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        InitPoPuWindow();
        more_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 弹出框（搜索，群发短信，新增用户）
                // morePopu存在就dismiss,不存在就show
                if (morePoPu.isShowing())
                    morePoPu.dismiss();
                else
                    morePoPu.showAsDropDown(more_btn, 0, 0);
            }
        });

        // 取消
        cancel_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dissSelect();
            }
        });

        // 确定群发
        sure_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> tel = new ArrayList<String>();
                customerList.clear();
                if (getcustomer != null && getcustomer.getCustomerList() != null) {
                    for (int o = 0; o < getcustomer.getCustomerList().size(); o++) {
                        if (getcustomer.getCustomerList().get(o).isIsselect()) {
                            tel.add(getcustomer.getCustomerList().get(o).getMobile());
                            CustomerListinfo c = new CustomerListinfo();
                            c.setCustomerId(getcustomer.getCustomerList().get(o).getCustomerId());
                            customerList.add(c);
                        }
                    }
                } else {
                    EmmApplication.T("当前没有客户");
                    return;
                }
                if (tel.size() < 1) {
                    PopuContent.poPu(NotSignedActivity.this, "还未选择客户", false, 0);
                } else {
                    dissSelect();
                    if (suretype == 0) {// 短信
                        EmmApplication.sendMMS(tel);
                    } else if (suretype == 1) {// 指派
                    }
                }
            }
        });

        // 排序
        tcSort.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                colors_text.setTextColor(Color.parseColor("#FD593E"));
                colors_text2.setTextColor(Color.parseColor("#3E3C3D"));
                icon1.setImageResource(R.drawable.paixu_down);
                icon2.setImageResource(R.drawable.shaixuan_up);
                setSortPoPu();// 排序菜单
            }
        });

        // 筛选
        lvScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                colors_text.setTextColor(Color.parseColor("#3E3C3D"));
                colors_text2.setTextColor(Color.parseColor("#FD593E"));
                icon1.setImageResource(R.drawable.paixu_up);
                icon2.setImageResource(R.drawable.shaixuan_down);
                Setscreen();// 筛选菜单
            }
        });

        // 客户列表
        swip_list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.w(TAG, "a--" + position);
                if (position == 0) {// 不处理
                } else {// 否则减去头部占用的一个位置
                    position--;
                    if (IsDrop) {
                        // 是否在加载客户详情 false 否 true 是 (作用：限制在加载客户详情界面时重复启动该界面)
                        if (EmmApplication.IsLoadingCustomer) {
                            Log.v(TAG, "正在跳转客户详情，该次操作无效");
                            return;
                        }
                        final String customerId =  getcustomer.getCustomerList().get(position).getCustomerId();
                        WebActivity.Companion.jump2CustomerDetail(activity, customerId);
                    }
                }
                Log.w(TAG, "b--" + position);
            }
        });
    }

    @Override
    protected void onResume() {
        Log.v(TAG, "onResume");
        BaseActivity.activity = this;

        if (EmmApplication.IS_RELOAD) {// 客户列表是否刷新
            EmmApplication.IS_RELOAD = false;
            EmmApplication.IsReloadMain = true;
            Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
            pageNumber = 1;

            getCustomerList("" + setSelect, itemid1, itemid2, "" + 1, "" + pageSize, 1, TYPED);
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        // 初始化（清空数据再关闭页面）
        getcustomer = new GetCustomerList();
        super.onDestroy();
    }

    /**
     * <p>
     * <b>Title：</b> 取消选择模式
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:13:56
     */
    private void dissSelect() {
        if (adapter != null) {
            adapter.getIsv(false);// 改变item展示状态

            if (null != getcustomer) {
                try {
                    for (int o = 0; o < getcustomer.getCustomerList().size(); o++) {
                        if (getcustomer.getCustomerList().get(o).isIsselect()) {
                            getcustomer.getCustomerList().get(o).setIsselect(false);
                        }
                    }
                } catch (NullPointerException e) {
                    Log.v(TAG, "getcustomer   null ");
                }
            }

            // 布局更新
            adapter.notifyDataSetChanged();
            cancel_btn.setVisibility(View.GONE);
            sure_btn.setVisibility(View.GONE);
            lvSelectNotSigned.setVisibility(View.VISIBLE);
            more_btn.setVisibility(View.VISIBLE);
            btBack.setVisibility(View.VISIBLE);
            IsDrop = true;
        }
    }

    /**
     * <p>
     * <b>Title：</b> 配置listview的item侧滑菜单
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:14:07
     */
    private void initMenuListView() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {

                // 配置侧滑菜单

                SwipeMenuItem openItem = new SwipeMenuItem(NotSignedActivity.this);
                openItem.setBackground(new ColorDrawable(Color.parseColor("#F82B49")));
                openItem.setWidth(dp2px(90));
                openItem.setIcon(R.drawable.xq_icon_tel);
                openItem.setTitle("打电话  ");
                openItem.setTitleSize(14);
                openItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem);

                SwipeMenuItem openItems = new SwipeMenuItem(NotSignedActivity.this);
                openItems.setBackground(new ColorDrawable(Color.parseColor("#FF6253")));
                openItems.setWidth(dp2px(90));
                openItems.setIcon(R.drawable.xq_icon_email);
                openItems.setTitle("发短信  ");
                openItems.setTitleSize(14);
                openItems.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItems);

                SwipeMenuItem openItem3 = new SwipeMenuItem(NotSignedActivity.this);
                openItem3.setBackground(new ColorDrawable(Color.parseColor("#FF7200")));
                openItem3.setWidth(dp2px(90));

                openItem3.setIcon(R.drawable.xq_icon_edit);
                openItem3.setTitle("写跟进  ");
                openItem3.setTitleSize(14);
                openItem3.setTitleColor(Color.WHITE);
                menu.addMenuItem(openItem3);

            }
        };
        swip_list.setMenuCreator(creator);
        // 侧滑菜单的相应事件
        swip_list.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:// 第一个添加的菜单的响应事件
                        Log.w("侧滑菜单的相应事件1", "被点击");
                        EmmApplication.callPhone(getcustomer.getCustomerList().get(position).getMobile(), getcustomer
                                .getCustomerList().get(position).getCustomerId());
                        break;
                    case 1:// 第二个添加的菜单的响应事件
                        Log.w("侧滑菜单的相应事件2", "被点击");
                        List<String> l = new ArrayList<String>();
                        l.add(getcustomer.getCustomerList().get(position).getMobile());
                        EmmApplication.sendMMS(l);
                        break;
                    case 2:// 第三个添加的菜单的响应事件
                        Log.w("侧滑菜单的相应事件3", "被点击" + position);
                        Intent intent = new Intent(NotSignedActivity.this, FollowUpActivity.class);
                        intent.putExtra("customerId", getcustomer.getCustomerList().get(position).getCustomerId());
                        intent.putExtra("SEX", getcustomer.getCustomerList().get(position).getCustomerSex());
                        intent.putExtra("NUMBER", getcustomer.getCustomerList().get(position).getIntentionLevel());
                        intent.putExtra("CUSTOMERSTATUS", getcustomer.getCustomerList().get(position).getCustomerStatus());
                        intent.putExtra("CUSTOMERORIGIN", getcustomer.getCustomerList().get(position).getCustomerOrigin());
                        intent.putExtra("STAR", getcustomer.getCustomerList().get(position).getStar());
                        intent.putExtra("NAME", getcustomer.getCustomerList().get(position).getCustomerName());
                        intent.putExtra("TEL", getcustomer.getCustomerList().get(position).getMobile());
                        startActivity(intent);
                        break;
                    case 3:// 第三个添加的菜单的响应事件
                        Log.w("侧滑菜单的相应事件4", "被点击");
                        List<String> listname = new ArrayList<String>();
                        for (int u = 0; u < 10; u++) {
                            listname.add("Name:" + u);
                        }
                        SetzpPopu(listname);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    // 将dp转化为px
    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    /**
     * 刷新
     */
    @Override
    public void onRefresh() {
        swip_list.stopLoadMore();// 关闭加载更多动画
        h.sendEmptyMessage(1);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        swip_list.stopRefresh();// 关闭刷新动画
        h.sendEmptyMessage(2);
    }

    /**
     * 模拟加载效果
     */
    @SuppressLint("HandlerLeak")
    Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {// 刷新
                pageNumber = 1;
                getCustomerList("" + setSelect, itemid1, itemid2, "" + 1, "" + pageSize, 1, TYPED);
            } else if (msg.what == 2) {// 加载更多
                pageNumber++;
                getCustomerList("" + setSelect, itemid1, itemid2, "" + pageNumber, "" + pageSize, 2, TYPED);
            }
        }

        ;
    };

    /**
     * <p>
     * <b>Title：</b> 初始化菜单PopupWindow
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:14:19
     */
    @SuppressWarnings("deprecation")
    public void InitPoPuWindow() {
        view = LayoutInflater.from(NotSignedActivity.this).inflate(R.layout.morep, null);
        morePoPu = new PopupWindow(view, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        // 设置焦点
        morePoPu.setFocusable(true);
        morePoPu.setOutsideTouchable(true);
        // view的焦点
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        // 监听back按钮
        view.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    morePoPu.dismiss();
                }
                return false;
            }
        });
        // 点击popupwindow范围外,popupwindow消失
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
            }
        });

        LinearLayout search = (LinearLayout) view.findViewById(R.id.search);
        LinearLayout sms = (LinearLayout) view.findViewById(R.id.sms);
        LinearLayout add_coustomer = (LinearLayout) view.findViewById(R.id.add_coustomer);
        LinearLayout allot = (LinearLayout) view.findViewById(R.id.allot);
        LinearLayout add_form = (LinearLayout) view.findViewById(R.id.add_form);
        LinearLayout add_phone = (LinearLayout) view.findViewById(R.id.add_phone);

        add_form.setVisibility(View.GONE);
        add_phone.setVisibility(View.GONE);
        add_coustomer.setVisibility(View.GONE);
        allot.setVisibility(View.GONE);

        View lines_2 = view.findViewById(R.id.lines_2);
        View lines_3 = view.findViewById(R.id.lines_3);
        View lines_3s = view.findViewById(R.id.lines_3s);
        View lines_4 = view.findViewById(R.id.lines_4);

        lines_3s.setVisibility(View.GONE);
        lines_4.setVisibility(View.GONE);
        lines_3.setVisibility(View.GONE);
        lines_2.setVisibility(View.GONE);

        // 搜索
        search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                Intent intent = new Intent();
                intent.putExtra("TYPE", "" + 2);
                intent.putExtra("TYPED", TYPED);
                intent.setClass(NotSignedActivity.this, SearchCustomerActivity.class);
                startActivity(intent);
            }
        });

        // 新增
        add_coustomer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                morePoPu.dismiss();
                WebActivity.Companion.jump2AddCustomer(activity);
            }
        });

        // 群发短信
        sms.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                suretype = 0;
                morePoPu.dismiss();
                if (adapter == null || null == getcustomer || null == getcustomer.getCustomerList()) {
                    PopuContent.poPu(NotSignedActivity.this, "当前没有客户", false, 0);
                } else {
                    adapter.getIsv(true);
                    adapter.notifyDataSetChanged();
                    cancel_btn.setVisibility(View.VISIBLE);
                    sure_btn.setVisibility(View.VISIBLE);
                    lvSelectNotSigned.setVisibility(View.GONE);
                    more_btn.setVisibility(View.GONE);
                    btBack.setVisibility(View.GONE);
                    IsDrop = false;
                }
            }
        });

        // 批量指派
        allot.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                suretype = 1;
                morePoPu.dismiss();
                adapter.getIsv(true);
                adapter.notifyDataSetChanged();
                cancel_btn.setVisibility(View.VISIBLE);
                sure_btn.setVisibility(View.VISIBLE);
                lvSelectNotSigned.setVisibility(View.GONE);
                more_btn.setVisibility(View.GONE);
                btBack.setVisibility(View.GONE);
                IsDrop = false;
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 排序菜单
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:14:45
     */
    @SuppressLint("WrongConstant")
    public void setSortPoPu() {
        viewSort = LayoutInflater.from(NotSignedActivity.this).inflate(R.layout.popu_sort, null);
        poPuSort = new PopupWindow(viewSort, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        poPuSort.setFocusable(true);
        poPuSort.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        poPuSort.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        poPuSort.showAtLocation(tcSort, Gravity.TOP, 0, 0);
        poPuSort.setFocusable(true);
        poPuSort.setOutsideTouchable(true);
        viewSort.setFocusable(true);
        viewSort.setFocusableInTouchMode(true);
        viewSort.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    poPuSort.dismiss();
                    EmmApplication.setLog(NotSignedActivity.this);
                }
                return false;
            }
        });

        viewSort.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuSort.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
            }
        });

        // 最新创建
        TextView newCreate = (TextView) viewSort.findViewById(R.id.new_creaete);
        // 最新更新
        TextView newUpdate = (TextView) viewSort.findViewById(R.id.new_update);
        // 最新跟进
        TextView newFgo = (TextView) viewSort.findViewById(R.id.new_fgo);
        // 按标星
        TextView numberStar = (TextView) viewSort.findViewById(R.id.number_star);

        TextView linesBlStar = (TextView) viewSort.findViewById(R.id.lines_bl_star);

        if (EmmApplication.isTips()) {
            newFgo.setText("暂未跟进(默认)");
        }

        numberStar.setVisibility(View.GONE);
        linesBlStar.setVisibility(View.GONE);

        ImageView g1 = (ImageView) viewSort.findViewById(R.id.g1);
        ImageView g2 = (ImageView) viewSort.findViewById(R.id.g2);
        ImageView g3 = (ImageView) viewSort.findViewById(R.id.g3);

        // 选中的显示勾选
        g1.setVisibility(setSelect == 1 ? View.VISIBLE : View.INVISIBLE);
        g2.setVisibility(setSelect == 2 ? View.VISIBLE : View.INVISIBLE);
        g3.setVisibility(setSelect == 3 ? View.VISIBLE : View.INVISIBLE);

        // 选中的显示橙色
        newCreate.setTextColor(setSelect == 1 ? Color.parseColor("#FD593E") : Color.parseColor("#494949"));
        newUpdate.setTextColor(setSelect == 2 ? Color.parseColor("#FD593E") : Color.parseColor("#494949"));
        newFgo.setTextColor(setSelect == 3 ? Color.parseColor("#FD593E") : Color.parseColor("#494949"));

        // 最新创建
        newCreate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuSort.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
                setSelect = 1;
                pageNumber = 1;
                Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
                getCustomerList();
            }
        });

        // 最近更新
        newUpdate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuSort.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
                setSelect = 2;
                pageNumber = 1;
                Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
                getCustomerList();
            }
        });

        // 最新跟进
        newFgo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuSort.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
                setSelect = 3;
                pageNumber = 1;
                Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
                getCustomerList();
            }
        });

        // 按星标
        numberStar.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuSort.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
            }
        });
    }

    private void getCustomerList() {
        getCustomerList("" + setSelect, itemid1, itemid2, "" + pageNumber, "" + pageSize, 1, TYPED);
    }

    /**
     * 主 筛选选中
     */
    private int select_id = 0;

    /**
     * 次 筛选
     */
    private int select_id2 = 0;

    /**
     * 首次接触方式 选中ID
     */
    String FirstContactModestr = "";

    /**
     * 筛选主菜单ID
     */
    String itemid1 = "1";

    /**
     * 筛选子菜单ID
     */
    String itemid2;

    /**
     * <p>
     * <b>Title：</b> 筛选菜单
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:14:57
     */
    @SuppressLint("WrongConstant")
    public void Setscreen() {
        viewScreen = LayoutInflater.from(NotSignedActivity.this).inflate(R.layout.popu_screen, null);
        poPuScreen = new PopupWindow(viewScreen, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        poPuScreen.setFocusable(true);
        poPuScreen.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        poPuScreen.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        poPuScreen.showAtLocation(tcSort, Gravity.TOP, 0, 0);
        poPuScreen.setFocusable(true);
        poPuScreen.setOutsideTouchable(true);
        viewScreen.setFocusable(true);
        viewScreen.setFocusableInTouchMode(true);
        viewScreen.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    poPuScreen.dismiss();
                    EmmApplication.setLog(NotSignedActivity.this);
                }
                return false;
            }
        });
        viewScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuScreen.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
            }
        });

        ListView screen_listview1 = (ListView) viewScreen.findViewById(R.id.screen_listview1);
        ListView screen_listview2 = (ListView) viewScreen.findViewById(R.id.screen_listview2);

        // 初始化筛选数据
        final List<ScreenOneModel> listm = new ArrayList<ScreenOneModel>();
        for (int i = 0; i < 4; i++) {
            ScreenOneModel sd = new ScreenOneModel();
            List<Info> listc = new ArrayList<Info>();
            if (i == 0) {
                sd.setName1("客户状态");
                sd.setNameid1("1");

                Info n0 = new Info();
                n0.setName2("全部");
                n0.setNameid("0");
                listc.add(n0);

                Info n = new Info();
                n.setName2("问询");
                n.setNameid("1");
                listc.add(n);

                Info n1 = new Info();
                n1.setName2("来访");
                n1.setNameid("2");
                listc.add(n1);

                if ("1".equals(EmmApplication.getData(EmmApplication.FROMDETAILSTYPE))) {// 拥有认筹权限
                    Info n2 = new Info();
                    n2.setName2("认筹");
                    n2.setNameid("3");
                    listc.add(n2);
                }

                Info n4 = new Info();
                n4.setName2("认购");
                n4.setNameid("4");
                listc.add(n4);

                Info n6 = new Info();
                n6.setName2("签约");
                n6.setNameid("5");
                listc.add(n6);

                Info n7 = new Info();
                n7.setName2("无意向");
                n7.setNameid("6");
                listc.add(n7);

                sd.setInfo(listc);
                listm.add(sd);
            } else if (i == 1) {
                sd.setName1("意向等级");
                sd.setNameid1("2");

                Info n0 = new Info();
                n0.setName2("全部");
                n0.setNameid("0");
                listc.add(n0);

                Info n = new Info();
                n.setName2("A+");
                n.setNameid("1");
                listc.add(n);

                Info n1 = new Info();
                n1.setName2("A");
                n1.setNameid("2");
                listc.add(n1);

                Info n2 = new Info();
                n2.setName2("B");
                n2.setNameid("3");
                listc.add(n2);

                Info n3 = new Info();
                n3.setName2("C");
                n3.setNameid("4");
                listc.add(n3);

                Info n4 = new Info();
                n4.setName2("D");
                n4.setNameid("5");
                listc.add(n4);
                sd.setInfo(listc);
                listm.add(sd);
            } else if (i == 2) {
                sd.setName1("首次接触方式");
                sd.setNameid1("4");

                Info n0 = new Info();
                n0.setName2("全部");
                n0.setNameid("0");
                listc.add(n0);

                if (FirstContactMode != null && FirstContactMode.size() > 0) {
                    for (int y = 0; y < FirstContactMode.size(); y++) {
                        Info n = new Info();
                        n.setName2(FirstContactMode.get(y).getDictionaryName());
                        n.setNameid(FirstContactMode.get(y).getDictionaryId());
                        listc.add(n);
                    }
                    sd.setInfo(listc);
                } else {
                }
                listm.add(sd);
            }
        }

        final ScreenONEAdapter adapter = new ScreenONEAdapter(NotSignedActivity.this, listm);
        final ScreenTWOAdapter adapter2 = new ScreenTWOAdapter(NotSignedActivity.this, listm.get(select_id).getInfo());
        // 绑定适配器
        screen_listview1.setAdapter(adapter);
        screen_listview2.setAdapter(adapter2);

        // 默认选中一项
        adapter.SetSelect(select_id);
        adapter2.SetSelect(select_id2);
        screen_listview2.setSelection(select_id2);

        // 列表item点击事件监听
        screen_listview1.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                adapter2.getDate(listm.get(arg2).getInfo(), select_id2);
                select_id = arg2;
                select_id2 = 0;

                itemid1 = listm.get(arg2).getNameid1();

                // 刷新主筛选列表的展示界面
                adapter.SetSelect(select_id);
                // 刷新次级筛选列表数据，以当前主筛选列表选中项为主键
                adapter2.SetSelect(select_id2);
            }
        });

        // 次级筛选列表item点击事件监听
        screen_listview2.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                poPuScreen.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
                select_id2 = arg2;

                // 刷新次级筛选列表的展示界面
                adapter2.SetSelect(select_id2);
                // 获取次级筛选菜单选中项的ID
                itemid2 = listm.get(select_id).getInfo().get(arg2).getNameid();

                pageNumber = 1;
                clearlist();
                // 调用接口数据，重新渲染客户列表

                Loading.showDialogForLoading(NotSignedActivity.this, "正在加载...", false, true, 60000);
                getCustomerList("" + setSelect, itemid1, itemid2, "" + pageNumber, "" + pageSize, 1, TYPED);
            }
        });
    }

    /**
     * <p>
     * <b>Title：</b> 清空list数据
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:17:33
     */
    private void clearlist() {
        getcustomer = new GetCustomerList();
        if (adapter == null) {
            adapter = new NotSignedAdapter(NotSignedActivity.this, null);
            swip_list.setAdapter(adapter);
        } else {
            adapter.setDate(null);
        }
    }

    /**
     * <p>
     * <b>Title：</b> 指派
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @param listname
     * @author tangxin
     * @date 2016年12月7日 下午4:17:47
     */
    @SuppressLint("WrongConstant")
    public void SetzpPopu(final List<String> listname) {
        viewZp = LayoutInflater.from(NotSignedActivity.this).inflate(R.layout.popu_zp, null);
        poPuZp = new PopupWindow(viewZp, android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT,
                android.support.v4.view.ViewPager.LayoutParams.FILL_PARENT);
        poPuZp.setFocusable(true);
        poPuZp.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        poPuZp.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        poPuZp.showAtLocation(viewZp, Gravity.BOTTOM, 0, 0);
        poPuZp.showAsDropDown(viewZp, 0, 0);
        poPuZp.setFocusable(true);
        poPuZp.setOutsideTouchable(true);
        viewZp.setFocusable(true);
        viewZp.setFocusableInTouchMode(true);
        viewZp.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    poPuZp.dismiss();
                    EmmApplication.setLog(NotSignedActivity.this);
                }
                return false;
            }
        });
        viewZp.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                poPuZp.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
            }
        });

        PickerView select_pick = (PickerView) viewZp.findViewById(R.id.select_pick);
        TextView shuerbtn = (TextView) viewZp.findViewById(R.id.shuerbtn);
        RelativeLayout relative_all = (RelativeLayout) viewZp.findViewById(R.id.relative_all);

        selectName = listname.get(0);

        // 设置数据到滑动选择控件
        select_pick.setData(listname);
        select_pick.setOnSelectListener(new onSelectListener() {
            @Override
            public void onSelect(String text, int id) {
                // 选中的
                selectName = text;
                SelectID = id;
            }
        });

        select_pick.setSelected(0);
        shuerbtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 确定
                poPuZp.dismiss();
                EmmApplication.setLog(NotSignedActivity.this);
                EmmApplication.T("指派完成,指派给:" + selectName + "==>ID:" + SelectID);
            }
        });

        relative_all.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击事件消耗
            }
        });

    }

    /**
     * 客户列表
     */
    GetCustomerList getcustomer;

    /**
     * 页码
     */
    int pageNumber = 1;

    /**
     * 页码条数
     */
    int pageSize = 10;

    boolean IsLoading = true;

    /**
     * 客户列表<br>
     * sort 排序<br>
     * screenType 筛选类型<br>
     * screenValue 筛选类型对应值 <br>
     * pageNumber 页码<br>
     * pageSize 页码大小 opentype 1 刷新 2 加载
     */
    private void getCustomerList(String sort, String screenType, String screenValue, String pageNumberd,
                                 String pageSized, final int opentype, String type) {
        EmmApplication.updateUrl("getCustomerList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("projectCode", EmmApplication.getProjectCode());
        map.put("type", type);
        map.put("sort", sort);
        if (!EmmApplication.isNull(screenType)) {
            map.put("screenType", "");
        } else {
            map.put("screenType", screenType);
        }
        if (!EmmApplication.isNull(screenValue)) {
            map.put("screenValue", "");
        } else {
            map.put("screenValue", screenValue);
        }
        map.put("pageNumber", pageNumberd);
        map.put("pageSize", pageSized);

        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getCustomerList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束error:" + error + "==" + content);
                swip_list.stopRefresh();
                String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
                swip_list.setRefreshTime(timed);
                swip_list.stopLoadMore();
                EmmApplication.setData("RefreshTime", timed);
            }

            @Override
            public void onFinish() {
                Loading.hideDialogForLoading();
                Log.v(TAG, "请求结束");
                swip_list.stopRefresh();
                String timed = EmmApplication.dataTime(EmmApplication.geTime(), "yyyy-MM-dd HH:mm");
                swip_list.setRefreshTime(timed);
                EmmApplication.setData("RefreshTime", timed);
                swip_list.stopLoadMore();
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "content-->:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }

                GetCustomerList getcust = JSONObject.parseObject(resData.toString(), GetCustomerList.class);
                if ("1".equals(getcust.getResult())) {
                    Log.v("获取成功", "");
                    try {
                        if (getcust.getCustomerList() != null) {
                            if (opentype == 1) {// 刷新
                                getcustomer = new GetCustomerList();
                                getcustomer = getcust;
                            } else {// 加载
                                if (getcustomer != null && getcustomer.getCustomerList() != null) {
                                    getcustomer.getCustomerList().addAll(getcust.getCustomerList());
                                } else {
                                    getcustomer = new GetCustomerList();
                                    getcustomer.getCustomerList().addAll(getcust.getCustomerList());
                                }
                            }
                            if (getcustomer.getCustomerList().size() < (pageNumber * pageSize)) {// 代表没有更多
                                IsLoading = false;
                            }
                            if (adapter == null) {
                                adapter = new NotSignedAdapter(NotSignedActivity.this, getcustomer.getCustomerList());
                                swip_list.setAdapter(adapter);
                            } else {
                                adapter.setDate(getcustomer.getCustomerList());
                            }
                        } else {
                            if (pageNumber > 0 && opentype != 1)
                                pageNumber--;
                            if (opentype == 1) {
                                EmmApplication.Ts("没有查询到客户");
                                ArrayList<CustomerList> list = new ArrayList<CustomerList>();
                                if (adapter == null) {
                                    adapter = new NotSignedAdapter(NotSignedActivity.this, list);
                                    swip_list.setAdapter(adapter);
                                } else {
                                    adapter.setDate(list);
                                }
                            } else {
                                EmmApplication.Ts("没有更多客户");
                            }
                        }
                    } catch (NullPointerException e) {
                        e.printStackTrace();
                    }
                } else {
                    EmmApplication.T(getcust.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getcust.getErrorCode().toString() + "errorMsg:"
                            + getcust.getErrorMsg().toString());
                }
            }
        });
    }

    /**
     * 首次接触方式
     */
    ArrayList<RqBusNumList> FirstContactMode;

    /**
     * 字典数据源
     */
    GetDictionaryList getdiction;

    /**
     * <p>
     * <b>Title：</b> 查询字典列表接口
     * </p>
     * <p>
     * <b>Description：</b>
     * </p>
     *
     * @author tangxin
     * @date 2016年12月7日 下午4:18:18
     */
    private void getDictionaryList() {
        EmmApplication.updateUrl("getDictionaryList");
        Map<String, String> map = new HashMap<String, String>();
        map.put("version", EmmApplication.getPackageManager(5));
        map.put("merchantId", EmmApplication.getData(EmmApplication.merchantId));
        map.put("token", EmmApplication.getToken());
        map.put("userId", EmmApplication.getUserId());
        map.put("terminalCode", EmmApplication.getPackageManager(2));
        map.put("busNumType", "11");
        map.put("busNum", "01");
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("params", map);
        JSONObject json = new JSONObject(paramsMap);
        String jsonstr = json.toString();
        RequestParams params = new RequestParams();
        params.put("body", jsonstr);
        Log.v("getDictionaryList-->post", EmmApplication.urlStr + "?body=" + jsonstr);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        asyncHttpClient.post(EmmApplication.urlStr, params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
                Log.v(TAG, "请求结束error:" + error + "==" + content);
            }

            @Override
            public void onFinish() {
                Log.v(TAG, "请求结束");
                super.onFinish();
            }

            @Override
            public void onStart() {
                super.onStart();
                Log.v(TAG, "请求开始");
            }

            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                if (content == null) {
                    return;
                }
                Log.v(TAG, "content==:" + content);
                JSONObject jsonObj = JSONObject.parseObject(content);
                JSONObject resData = (JSONObject) jsonObj.get("resData");
                if (resData == null) {
                    Log.v(TAG, "信息返回值为空");
                    return;
                }
                getdiction = JSONObject.parseObject(resData.toString(), GetDictionaryList.class);
                if ("1".equals(getdiction.getResult())) {
                    FirstContactMode = getdiction.getRqBusNumList();
                } else {
                    EmmApplication.T(getdiction.getErrorMsg().toString());
                    Log.v("获取失败", "errorCode:" + getdiction.getErrorCode().toString() + "errorMsg:"
                            + getdiction.getErrorMsg().toString());
                }
            }
        });
    }

}
